package com.example.notice.news

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.base.entity.NewsEntityItem
import com.example.base.net.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class NewsDataSource(val apiService: ApiService):PagingSource<Int,NewsEntityItem>() {
    override fun getRefreshKey(state: PagingState<Int, NewsEntityItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NewsEntityItem> {
        return withContext(Dispatchers.IO){
            try {
                val res = apiService.news().first()
                if(res.code==200){
                    LoadResult.Page(res.data,null,null)
                }else{
                    LoadResult.Error(Exception(res.message))
                }
            }catch (e:Exception){
                LoadResult.Error(Exception(e))
            }
        }
    }
}